import { Text, View } from '@tarojs/components';
import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { ArrowLeft } from '@nutui/icons-react-taro';
import './index.less';
import { observer } from 'mobx-react-lite';

interface IProps {
  className?: string;
  style?: {},
  title?: string;
  bgColor?: string;
  mode?: 'back' | 'home';
  color?: string;
  isSlot?: boolean;
  SlotComp?: Function;
  onClickBack?: Function;

  [pro: string]: any;
}

function Navbar(props: IProps) {

  const [navbarHeight, setNavbarHeight] = useState(0);

  useEffect(() => {
    const {statusBarHeight} = Taro.getSystemInfoSync();
    statusBarHeight ? setNavbarHeight(statusBarHeight + 44) : 0;
  }, []);

  return (() => {
    const {
      className = '',
      style = {},
      title = '',
      bgColor = 'var(--bg-first)',
      mode = '',
      color = 'var(--font-first)',
      isSlot = false,
      SlotComp,
      onClickBack
    } = props;

    const [canBack, setCanBack] = useState(false);

    const handleBack = async () => {
      if (!onClickBack) {
        setCanBack(true);
        return;
      }
      await onClickBack();
      setCanBack(true);
    };

    useEffect(() => {
      if (canBack) {
        Taro.navigateBack();
        setCanBack(false);
      }
    }, [canBack]);
    return (
      <View className={ `light ${ className } page-container` } style={ style }>
        <View
          className='page-navbar'
          style={
            {
              display: mode ? 'flex' : 'none',
              minHeight: navbarHeight + 'px',
              paddingTop: (navbarHeight - 36) + 'px',
              backgroundColor: bgColor,
              color
            }
          }>
          {
            isSlot ?
              SlotComp && SlotComp() :
              (<View className='navbar-header'>
                {
                  mode === 'back' &&
                    <View className='navbar-left-arrow' onClick={ handleBack }>
                      <ArrowLeft/> 
                    </View>
                }
                <Text>{ title }</Text>
              </View>)
          }
        </View>
        { props.children }
      </View>
    );
  })();
}

export default observer(Navbar);
